<template>
  <common-dialog ref="dialog" width="500px" :title="title" :inDialog="inDialog" 
    @closed="onClosed" @close="onClose">
    <common-form ref="form" :rules="rules" :data="data"  @keyup.enter.native="save"> 
      <el-divider>接口信息</el-divider>
      <el-form-item label="接口名称" prop="name">
        <el-input v-model="data.name" placeholder="填写接口名称"></el-input>
      </el-form-item>
      <el-form-item label="接口路径" prop="path">
        <el-input v-model="data.path" placeholder="填写接口完整路径，不区分大小写"></el-input>
      </el-form-item>
    </common-form>
    <template #footer>
      <el-button type="primary" @click="save" :loading="$refs.dialog && $refs.dialog.isLoading">保存</el-button>
    </template>
  </common-dialog>
</template>
<script>
import commonDialog from "@/components/common/dialog.vue";
import commonForm from "@/components/common/form.vue";
import api from "@/api/sys/api";

export default {
  components: { commonDialog, commonForm },
  props: {
    inDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      data: {
        id: 0,
        name: "",
        path: ""
      },
      title: "",
      isSaved: false,
      rules: {
        name: [
          { required: true, message: "请填写接口名称" },
          {
            validator: this.$commonJs.validateRules.createCheckExist(
              api.checkExistByName,
              this,
              "data.id",
              "名称已重复"
            ),
            trigger: "blur"
          }
        ],
        path: [
          { required: true, message: "请填写接口路径" },
          {
            validator: this.$commonJs.validateRules.createCheckExist(
              api.checkExistByPath,
              this,
              "data.id",
              "路径已重复"
            ),
            trigger: "blur"
          }
        ]
      }
    };
  },
  computed: {
    commonDialog() {
      return this.$refs.dialog;
    }
  },
  mounted() { },
  methods: {
    async showCreate() {
      this.title = "创建接口";
      await this.$refs.dialog.show();
    },
    async showEdit(data) {
      this.title = "编辑接口";
      await this.$refs.dialog.show();
      this.$refs.form.setData(data);
    },
    //窗口关闭后
    onClosed() {      
      this.title = "";
      this.isSaved = false;
      this.$refs.form.reset();
    },
    //窗口关闭时
    onClose(){
      if(this.isSaved){
        this.$emit("close-saved");        
      }
    },
    async save() {
      this.$refs.dialog.loading();
      const valid = await this.$refs.form.validate();
      if (!valid) {
        this.$refs.dialog.loading(false);
        return;
      }
      const res = await api.save(this.data);
      this.$refs.dialog.loading(false);
      if (res.code != 0) {
        return;
      }
      this.data.id = res.data;
      this.isSaved = true;
      this.$message.success("保存成功");
    }
  }
};
</script>